package com.m4f.business.service.impl;

import java.util.Collection;
import java.util.List;
import java.util.logging.Logger;

import com.m4f.business.domain.InternalUser;
import com.m4f.business.service.ifc.UserService;
import com.m4f.cityclient.api.models.UserCity;
import com.m4f.cityclient.common.model.M4FOAuthUser;
import com.m4f.gaeweb.business.service.impl.DAOBaseService;
import com.m4f.gaeweb.persistence.dao.ifc.DAOSupport;

public class UserServiceImpl extends DAOBaseService implements UserService {
	
	private static final Logger LOGGER = Logger.getLogger(UserServiceImpl.class.getName());
	
	public UserServiceImpl(DAOSupport dao) {
		super(dao);
	}

	@Override
	public InternalUser createUser() {
		return (InternalUser) this.DAO.createInstance(InternalUser.class);
	}

	@Override
	public void delete(InternalUser user) throws Exception {
		this.DAO.delete(user);
	}

	@Override
	public List<InternalUser> getAllUser() throws Exception {
		return this.DAO.findAll(InternalUser.class);
	}

	@Override
	public InternalUser getUser(Long id) throws Exception {
		return (InternalUser) this.DAO.findById(InternalUser.class, id);
	}

	@Override
	public InternalUser getUser(String email) throws Exception {
		return this.DAO.findEntity(InternalUser.class, "email == emailParam", 
				"String emailParam", new String[]{email});
	}

	@Override
	public void save(InternalUser user) throws Exception {
		this.DAO.saveOrUpdate(user);
	}
	
	@Override
	public long countUsers() throws Exception {
		return this.DAO.count(InternalUser.class);
	}

	@Override
	public Collection<InternalUser> getUsersByRange(String ordering, int init, int end)
			throws Exception {
		return this.DAO.findEntitiesByRange(InternalUser.class, ordering, init, end);
	}
	
	// FROM M4FOAuthUserService interface
	@Override
	public M4FOAuthUser createUser(UserCity userCity) {
		M4FOAuthUser user = new InternalUser(userCity);
		
		return user;
	}

	@Override
	public void save(M4FOAuthUser user) throws Exception {
		if(user instanceof InternalUser) {
			InternalUser internalUser = (InternalUser) user;
			this.save(internalUser);
		} else {
			throw new Exception("Incorrect type of User!!!"); // TODO
		}
	}
}